<template>
  <div class="system-config-manager">
    <!-- 头部信息 -->
    <div class="header">
      <div class="page-info">
        <h1 class="page-title">系统配置管理</h1>
        <div class="page-description">管理系统运行时配置信息，支持配置的增删改查操作</div>
      </div>
      <div class="action-buttons">
        <a-button type="primary" @click="showAddModal">
          <template #icon>
            <icon-plus />
          </template>
          新增配置
        </a-button>
        <a-button @click="handleExport">
          <template #icon>
            <icon-download />
          </template>
          导出数据
        </a-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-input-search
          v-model="searchKey"
          placeholder="搜索配置键或配置值..."
          style="width: 300px"
          @search="handleSearch"
      />
      <a-select v-model="filterStatus" placeholder="全部状态" style="width: 200px">
        <a-option value="">全部状态</a-option>
        <a-option value="active">启用中</a-option>
        <a-option value="inactive">已停用</a-option>
      </a-select>
      <a-button @click="refreshData">
        <template #icon>
          <icon-refresh />
        </template>
        刷新
      </a-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
          :columns="columns"
          :data="filteredData"
          :pagination="pagination"
          row-key="id"
      >
        <template #configValue="{ record }">
          <div class="json-view">
            {{ formatJsonValue(record.configValue) }}
          </div>
        </template>

        <template #status="{ record }">
          <span :class="['status-badge', record.status === 'active' ? 'status-active' : 'status-inactive']">
            {{ record.status === 'active' ? '启用中' : '已停用' }}
          </span>
        </template>

        <template #operations="{ record }">
          <div class="action-cell">
            <a-button type="text" size="mini" @click="handleEdit(record)">
              <template #icon>
                <icon-edit />
              </template>
              编辑
            </a-button>
            <a-button
                type="text"
                size="mini"
                status="danger"
                @click="handleDelete(record)"
            >
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </div>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑配置模态框 -->
    <a-modal
        v-model:visible="modalVisible"
        :title="isEditing ? '编辑配置' : '新增配置'"
        @ok="handleSave"
        @cancel="handleCancel"
        :width="600"
    >
      <a-form :model="formData" layout="vertical">
        <a-form-item label="配置键" field="configKey" :rules="[{ required: true, message: '配置键不能为空' }]">
          <a-input v-model="formData.configKey" placeholder="请输入配置键" />
        </a-form-item>

        <a-form-item label="配置值" field="configValue" :rules="[{ required: true, message: '配置值不能为空' }]">
          <a-textarea
              v-model="formData.configValue"
              placeholder='请输入JSON格式的配置值，例如: {"value": "示例配置"}'
              :auto-size="{ minRows: 3, maxRows: 6 }"
          />
        </a-form-item>

        <a-form-item label="状态" field="status">
          <a-radio-group v-model="formData.status">
            <a-radio value="active">启用</a-radio>
            <a-radio value="inactive">停用</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="备注" field="comment">
          <a-textarea v-model="formData.comment" placeholder="请输入配置项的备注信息" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认对话框 -->
    <a-modal v-model:visible="deleteConfirmVisible" title="确认删除" @ok="confirmDelete">
      <p>确定要删除配置项 "{{ currentItem?.configKey }}" 吗？此操作不可恢复。</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import {
  IconPlus,
  IconDownload,
  IconRefresh,
  IconEdit,
  IconDelete,
  IconSearch
} from '@arco-design/web-vue/es/icon';

// 表格列定义
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 60,
    render: (_, record, index) => index + 1
  },
  {
    title: '配置键',
    dataIndex: 'configKey',
    width: 150
  },
  {
    title: '配置值',
    slotName: 'configValue',
    ellipsis: true,
    tooltip: true
  },
  {
    title: '状态',
    slotName: 'status',
    width: 100
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 150
  },
  {
    title: '修改人',
    dataIndex: 'updateBy',
    width: 100
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    width: 150
  },
  {
    title: '操作',
    slotName: 'operations',
    width: 150
  }
];

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true
});

// 搜索和筛选条件
const searchKey = ref('');
const filterStatus = ref('');

// 模态框状态
const modalVisible = ref(false);
const deleteConfirmVisible = ref(false);
const isEditing = ref(false);

// 当前操作项
const currentItem = ref(null);

// 表单数据
const formData = reactive({
  id: '',
  configKey: '',
  configValue: '',
  status: 'active',
  comment: ''
});

// 模拟数据
const tableData = ref([]);

// 初始化数据
const initData = () => {
  tableData.value = [
    {
      id: '1',
      configKey: 'system.name',
      configValue: '{"value": "企业管理系统"}',
      status: 'active',
      createBy: 'admin',
      createTime: '2023-06-01 10:30:25',
      updateBy: 'admin',
      updateTime: '2023-06-15 14:22:18',
      comment: '系统名称配置'
    },
    {
      id: '2',
      configKey: 'system.theme',
      configValue: '{"mode": "light", "primaryColor": "#165DFF"}',
      status: 'active',
      createBy: 'admin',
      createTime: '2023-06-01 10:30:25',
      updateBy: 'liwei',
      updateTime: '2023-07-02 09:15:43',
      comment: '系统主题配置'
    },
    {
      id: '3',
      configKey: 'system.timeout',
      configValue: '{"login": 3600, "api": 300}',
      status: 'active',
      createBy: 'admin',
      createTime: '2023-06-01 10:30:25',
      updateBy: 'admin',
      updateTime: '2023-06-05 16:40:12',
      comment: '系统超时配置'
    },
    {
      id: '4',
      configKey: 'system.backup',
      configValue: '{"enable": true, "time": "02:00", "keepDays": 30}',
      status: 'inactive',
      createBy: 'liwei',
      createTime: '2023-06-12 14:20:35',
      updateBy: 'liwei',
      updateTime: '2023-06-20 11:05:27',
      comment: '系统备份配置'
    },
    {
      id: '5',
      configKey: 'system.log',
      configValue: '{"level": "info", "keepDays": 7, "maxSize": 100}',
      status: 'active',
      createBy: 'admin',
      createTime: '2023-06-01 10:30:25',
      updateBy: 'admin',
      updateTime: '2023-06-01 10:30:25',
      comment: '系统日志配置'
    }
  ];
  pagination.total = tableData.value.length;
};

// 过滤后的数据
const filteredData = computed(() => {
  let data = tableData.value;

  // 根据搜索关键词过滤
  if (searchKey.value) {
    const key = searchKey.value.toLowerCase();
    data = data.filter(item =>
        item.configKey.toLowerCase().includes(key) ||
        item.configValue.toLowerCase().includes(key)
    );
  }

  // 根据状态过滤
  if (filterStatus.value) {
    data = data.filter(item => item.status === filterStatus.value);
  }

  pagination.total = data.length;
  return data;
});

// 格式化JSON值显示
const formatJsonValue = (value) => {
  try {
    const obj = JSON.parse(value);
    return JSON.stringify(obj, null, 2);
  } catch (e) {
    return value;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.current = 1;
};

// 刷新数据
const refreshData = () => {
  initData();
};

// 显示新增模态框
const showAddModal = () => {
  isEditing.value = false;
  resetForm();
  modalVisible.value = true;
};

// 处理编辑
const handleEdit = (record) => {
  isEditing.value = true;
  currentItem.value = record;
  Object.assign(formData, record);
  modalVisible.value = true;
};

// 处理删除
const handleDelete = (record) => {
  currentItem.value = record;
  deleteConfirmVisible.value = true;
};

// 确认删除
const confirmDelete = () => {
  if (currentItem.value) {
    const index = tableData.value.findIndex(item => item.id === currentItem.value.id);
    if (index !== -1) {
      tableData.value.splice(index, 1);
      pagination.total = tableData.value.length;
    }
  }
  deleteConfirmVisible.value = false;
};

// 处理保存
const handleSave = () => {
  if (isEditing.value) {
    // 更新现有配置
    const index = tableData.value.findIndex(item => item.id === formData.id);
    if (index !== -1) {
      const now = new Date().toLocaleString();
      tableData.value[index] = {
        ...formData,
        updateBy: 'currentUser', // 实际应用中应从用户信息获取
        updateTime: now
      };
    }
  } else {
    // 添加新配置
    const now = new Date().toLocaleString();
    const newConfig = {
      ...formData,
      id: String(Date.now()),
      createBy: 'currentUser', // 实际应用中应从用户信息获取
      createTime: now,
      updateBy: 'currentUser',
      updateTime: now
    };
    tableData.value.push(newConfig);
    pagination.total = tableData.value.length;
  }
  modalVisible.value = false;
};

// 处理取消
const handleCancel = () => {
  modalVisible.value = false;
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: '',
    configKey: '',
    configValue: '',
    status: 'active',
    comment: ''
  });
};

// 处理导出
const handleExport = () => {
  // 这里可以实现导出逻辑
  console.log('导出数据');
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
});
</script>

<style scoped>
.system-config-manager {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.page-info {
  flex: 1;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.page-description {
  color: #86909c;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.search-bar {
  background: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
}

.table-container {
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.json-view {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-active {
  background-color: #f0f7ff;
  color: #165dff;
}

.status-inactive {
  background-color: #fff3e8;
  color: #ff7d00;
}

.action-cell {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-buttons {
    margin-top: 16px;
    width: 100%;
    justify-content: flex-end;
  }

  .search-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
